package com.hdu.hot100.arr;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class lc56 {
    class Solution {
        public int[][] merge(int[][] intervals) {
            Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
            int left = intervals[0][0];
            int right = intervals[0][1];
            List<int[]> ans = new ArrayList<>();
            for (int i = 1; i < intervals.length; i++)
            {
                if (right < intervals[i][0])
                {
                    ans.add(new int[]{left, right});
                    left = intervals[i][0];
                    right = intervals[i][1];
                }
                else
                {
                    right = Math.max(right, intervals[i][1]);
                }
            }
            ans.add(new int[]{left, right});
            return ans.toArray(new int[ans.size()][]);
        }
    }
}
